const { ListNode } = require('./base')

const getIntersectionNode1 = function (headA, headB) {
  let p = headA
  while (p.next) {
    p = p.next
  }
  p.next = headA
  let fast = headB
  let slow = headB
  while (fast && fast.next) {
    slow = slow.next
    fast = fast.next.next
    if (slow === fast) {
      slow = headB
      while (fast !== slow) {
        fast = fast.next
        slow = slow.next
      }
      p.next = null
      return slow
    }
  }
  p.next = null
  return null
}

const getIntersectionNode2 = function (headA, headB) {
  let p1 = headA
  let p2 = headB
  while (p1 !== p2) {
    if (!p1) {
      p1 = headB
    } else {
      p1 = p1.next
    }
    if (!p2) {
      p2 = headA
    } else {
      p2 = p2.next
    }
  }
  return p1
}
